<template>
  <div>
    <div v-clickoutside="hideReplyBtn" @click="inputFocus" class="my-reply">
      <el-avatar
        class="header-img"
        :size="40"
        :src="$store.state.imgShowRoad + '/file/' + myHeader"
      ></el-avatar>
      <div class="reply-info">
        <div
          tabindex="0"
          contenteditable="true"
          id="replyInput"
          spellcheck="false"
          placeholder="输入评论..."
          class="reply-input"
          @focus="showReplyBtn"
          @input="onDivInput($event)"
        ></div>
      </div>
      <div class="reply-btn-box" v-show="btnShow">
        <el-button
          class="reply-btn"
          size="medium"
          @click="sendComment"
          v-show="btnShow"
          type="primary"
          >发表评论</el-button
        >
      </div>
    </div>
    <div
      v-for="(item, i) in comments"
      :key="i"
      class="author-title reply-father"
    >
      <el-avatar
        class="header-img"
        :size="40"
        :src="$store.state.imgShowRoad + '/file/' + item.headImg"
      ></el-avatar>
      <div class="author-info">
        <span class="author-name">{{ item.userName }}</span>
      </div>
      <div class="talk-box">
        <p>
          <span class="reply">{{ item.discuss }}</span>
        </p>
        <div style="color: gray">
          <span class="author-time" style="margin-right: 15px">{{
            item.updateTime | formatTime
          }}</span>
          <span @click="showReplyInput(i, item.userName, item.orderDiscussId)">
            <a style="color: gray; cursor: pointer">回复</a
            >{{ item.commentNum }} <span>{{ item.likeStatus }} </span>
          </span>
          <i
            :class="[
              'iconfont-like',
              item.likeStatus === 1 ? 'icon-dianzan1' : 'icon-dianzan',
            ]"
            @click="toggleLike(item.orderDiscussId)"
            style="cursor: pointer; margin-left: 10px"
          ></i
          ><span>{{ item.likes }}</span>
        </div>
      </div>
      <div class="reply-box">
        <div
          v-for="(reply, j) in item.replyComments"
          :key="j"
          class="author-title"
        >
          <el-avatar
            class="header-img"
            :size="40"
            :src="$store.state.imgShowRoad + '/file/' + reply.headImg"
          ></el-avatar>
          <div class="author-info">
            <span class="author-name">{{ reply.userName }}</span>
            <span class="author-time">{{ reply.updateTime | formatTime }}</span>
          </div>
          <div class="icon-btn">
            <span
              @click="showReplyInput(i, reply.userName, reply.orderDiscussId)"
              ><i class="iconfont el-icon-s-comment"></i
              >{{ reply.commentNum }}</span
            >
            <i class="iconfont el-icon-caret-top"></i>{{ reply.likes }}
          </div>
          <div class="talk-box">
            <p>
              <span
                >回复 <b>{{ reply.replyUser }}</b
                >:</span
              >

              <span class="reply">{{ reply.discuss }}</span
              ><br />

              <span
                class="author-time"
                style="margin-right: 15px; color: gray"
                >{{ reply.updateTime | formatTime }}</span
              >
              <span
                @click="showReplyInput(i, reply.userName, reply.orderDiscussId)"
                ><a style="color: gray; cursor: pointer">回复</a
                >{{ reply.commentNum }}</span
              >
              <i
                :class="[
                  'iconfont-like',
                  reply.likeStatus === 1 ? 'icon-dianzan1' : 'icon-dianzan',
                ]"
                @click="toggleLike(reply.orderDiscussId)"
                style="cursor: pointer; margin-left: 10px"
              ></i
              ><span style="color: gray">{{ reply.likes }}</span>
              <span>{{ reply.likeStatus }}</span>
            </p>
          </div>
          <div class="reply-box"></div>
        </div>
      </div>
      <div v-show="_inputShow(i)" class="my-reply my-comment-reply">
        <div style="display: flex; align-items: center">
          <el-avatar
            class="header-img"
            :size="40"
            :src="$store.state.imgShowRoad + '/file/' + myHeader"
          ></el-avatar>
          <span style="margin-left: 8px"
            >回复：<b>{{ to }}</b></span
          >
        </div>
        <div class="reply-info">
          <div
            tabindex="0"
            contenteditable="true"
            spellcheck="false"
            placeholder="输入评论..."
            @input="onDivInput($event)"
            class="reply-input reply-comment-input"
          ></div>
        </div>
        <div class="reply-btn-box">
          <el-button
            class="reply-btn"
            size="medium"
            @click="sendCommentReply(i, j)"
            type="primary"
            >发表评论</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>


<script>
import {
  getOrderDiscussList,
  addOrderDiscuss,
  getUserLikeList,
  addLike,
  deleteLike
} from "../api/orderDiscuss";
import { loginSelectByUsername } from "../api/user";
const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e);
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.vueClickOutside = documentHandler;
    document.addEventListener("click", documentHandler);
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener("click", el.vueClickOutside);
    delete el.vueClickOutside;
  },
};

export default {
  // components: { UserAvatar },
  name: "ArticleComment",
  props: {
    orderId: {
      type: [String, Number], // 根据 orderId 的实际类型来设置
      required: true,
    },
  },
  data() {
    return {
      btnShow: false,
      index: "0",
      replyComment: "",
      myName: "",
      myHeader: "",
      myId: 19870621,
      to: "",
      toId: -1,
      comments: [],
    };
  },
  directives: { clickoutside },
  filters: {
    formatTime(value) {
      if (!value) return "";
      return value.replace("T", " ");
    },
  },
  mounted() {
    // 获取当前用户名
    // this.myName = this.$store.state.loginUserNickname

    // 用户头像$store.state.imgShowRoad + '/file/' + myHeader
    // this.myHeader = this.$store.state.loginUserAvatar

    loginSelectByUsername({}).then((res) => {
      this.myName = res.data.userName;
      this.myHeader = res.data.avatar;
    });

    getOrderDiscussList(this.orderId).then((res) => {
      alert(this.orderId);
      // 给每个评论和回复评论添加 inputShow 属性
      const addInputShow = (discussItems) => {
        discussItems.forEach((item) => {
          item.inputShow = false; // 默认值设置为 false
          item.reply = [];
          item.replyComments = item.replyComments || [];
          if (item.replyComments && item.replyComments.length > 0) {
            item.replyComments.forEach((reply) => {
              reply.inputShow = false; // 同样为回复评论设置默认值
            });
          }
        });
      };

      // 给 data 数组中的每个元素添加 inputShow 属性
      addInputShow(res.data);

      // 将处理后的数据赋值给 comments
      this.comments = res.data;

      this.getAllLikeInfo();
    });
  },
  methods: {
    toggleLike(orderDiscussId) {
      const updateLikeStatus = (items) => {
        items.forEach((item) => {
          const comment = item.replyComments
            ? item.replyComments.find(
                (reply) => reply.orderDiscussId === orderDiscussId
              )
            : item.orderDiscussId === orderDiscussId
            ? item
            : null;

          if (comment) {
            if(comment.likeStatus === 1){
              deleteLike(comment.orderDiscussId).then(res=>{

              })
            }
            else{
              addLike(comment.orderDiscussId).then(res=>{

              })
            }
            comment.likeStatus = comment.likeStatus === 1 ? 0 : 1;
            // 发送请求到后端更新点赞状态
            // 这里应该是一个 API 请求，例如：
            // updateLikeStatus(orderDiscussId, comment.likeStatus)
          }
        });
      };

      updateLikeStatus(this.comments);
      this.getAllLikeInfo();
    },
    getAllLikeInfo() {
      getUserLikeList()
        .then((response) => {
          if (response.flag && response.code === 20000) {
            const likedIds = response.data;
            this.updateCommentsLikeStatuses(likedIds);
          } else {
            console.error("获取点赞信息失败:", response.message);
          }
        })
        .catch((error) => {
          console.error("请求点赞信息出错:", error);
        });
    },
    updateCommentsLikeStatuses(likedIds) {
      const updateRepliesLikeStatus = (replies) => {
        return replies.map((reply) => ({
          ...reply,
          likeStatus: likedIds.includes(reply.orderDiscussId) ? 1 : 0,
        }));
      };

      this.comments = this.comments.map((comment) => ({
        ...comment,
        likeStatus: likedIds.includes(comment.orderDiscussId) ? 1 : 0,
        replyComments: updateRepliesLikeStatus(comment.replyComments),
      }));
    },
    inputFocus() {
      var replyInput = document.getElementById("replyInput");
      replyInput.style.padding = "8px 8px";
      replyInput.style.border = "2px solid blue";
      replyInput.focus();
    },
    showReplyBtn() {
      this.btnShow = true;
    },
    hideReplyBtn() {
      this.btnShow = false;
      replyInput.style.padding = "10px";
      replyInput.style.border = "none";
    },
    showReplyInput(i, name, id) {
      this.comments[this.index].inputShow = false;
      this.index = i;
      this.comments[i].inputShow = true;
      this.to = name;
      this.toId = id;

      this.replyComment += "@" + this.to + " ";
    },
    _inputShow(i) {
      return this.comments[i].inputShow;
    },
    sendComment() {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "评论不能为空",
        });
      } else {
        let a = {};
        let input = document.getElementById("replyInput");

        a.discuss = this.replyComment;
        a.headImg = this.myHeader;
        a.discussType = 0;
        a.orderId = this.orderId;
        a.replyNum = 0;
        a.likes = 0;
        this.comments.push(a);
        this.replyComment = "";
        input.innerHTML = "";
        console.log(a);
        // alert(a.discuss)
        addOrderDiscuss(a).then((res) => {
          // alert(res.message)
        });
      }
    },
    sendCommentReply(i, j) {
      if (!this.replyComment) {
        this.$message({
          showClose: true,
          type: "warning",
          message: "评论不能为空",
        });
      } else {
        // alert(aaa);
        let a = {};
        a.orderId = this.orderId;
        a.discuss = this.replyComment;
        a.discussType = 1;
        a.replyId = this.toId;
        a.replyNum = 0;
        a.likes = 0;
        a.headImg = this.myHeader;
        a.replyUser = this.to;
        this.comments[i].reply.push(a);
        this.replyComment = "";
        document.getElementsByClassName("reply-comment-input")[i].innerHTML =
          "";
        console.log(a.discuss);
        addOrderDiscuss(a).then((res) => {
          // alert(res.message)
        });
      }
    },
    onDivInput: function (e) {
      this.replyComment = e.target.innerHTML;
    },
    dateStr(date) {
      //获取js 时间戳
      var time = new Date().getTime();
      //去掉 js 时间戳后三位，与php 时间戳保持一致
      time = parseInt((time - date) / 1000);
      //存储转换值
      var s;
      if (time < 60 * 10) {
        //十分钟内
        return "刚刚";
      } else if (time < 60 * 60 && time >= 60 * 10) {
        //超过十分钟少于1小时
        s = Math.floor(time / 60);
        return s + "分钟前";
      } else if (time < 60 * 60 * 24 && time >= 60 * 60) {
        //超过1小时少于24小时
        s = Math.floor(time / 60 / 60);
        return s + "小时前";
      } else if (time < 60 * 60 * 24 * 30 && time >= 60 * 60 * 24) {
        //超过1天少于30天内
        s = Math.floor(time / 60 / 60 / 24);
        return s + "天前";
      } else {
        //超过30天ddd
        var date = new Date(parseInt(date));
        return (
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate()
        );
      }
    },
  },
};
</script>

<style scoped>
.slide-enter-active,
.slide-leave-active {
  transition: all 0.5s ease;
}
.slide-enter, .slide-leave-to /* .slide-leave-active in versions below 2.1.8 */ {
  transform: translateY(-100%);
  opacity: 0;
}
.my-reply {
  padding: 10px;
  /* background-color: #fafbfc; */
}
.my-reply .header-img {
  display: inline-block;
  vertical-align: top;
}
.my-reply .reply-info {
  display: inline-block;
  margin-left: 5px;
  width: 90%;
}
@media screen and (max-width: 1200px) {
  .my-reply .reply-info {
    width: 80%;
  }
}
.my-reply .reply-info .reply-input {
  min-height: 20px;
  line-height: 22px;
  padding: 10px 10px;
  color: #000;
  background-color: #eee;
  border-radius: 5px;
}
.my-reply .reply-info .reply-input:empty:before {
  content: attr(placeholder);
}
.my-reply .reply-info .reply-input:focus:before {
  content: none;
}
.my-reply .reply-info .reply-input:focus {
  padding: 8px 8px;
  border: 2px solid blue;
  box-shadow: none;
  outline: none;
}
.my-reply .reply-btn-box {
  height: 25px;
  margin: 10px 0;
}
.my-reply .reply-btn-box .reply-btn {
  position: relative;
  float: right;
  margin-right: 15px;
}
.my-comment-reply {
  margin-left: 50px;
}
.my-comment-reply .reply-input {
  width: flex;
}
.author-title:not(:last-child) {
  border-bottom: 1px solid rgba(178, 186, 194, 0.3);
}
.author-title {
  padding: 10px;
}
.author-title .header-img {
  display: inline-block;
  vertical-align: top;
}
.author-title .author-info {
  display: inline-block;
  margin-left: 5px;
  width: 60%;
  height: 40px;
  line-height: 20px;
}
.author-title .author-info > span {
  display: block;
  cursor: pointer;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.author-title .author-info .author-name {
  color: #000;
  font-size: 18px;
  font-weight: bold;
}
.author-title .author-info .author-time {
  font-size: 14px;
}
.author-title .icon-btn {
  width: 30%;
  padding: 0 !important;
  float: right;
}
@media screen and (max-width: 1200px) {
  .author-title .icon-btn {
    width: 20%;
    padding: 7px;
  }
}
.author-title .icon-btn > span {
  cursor: pointer;
}
.author-title .icon-btn .iconfont {
  margin: 0 5px;
}
.author-title .talk-box {
  margin: 0 50px;
}
.author-title .talk-box > p {
  margin: 0;
}
.author-title .talk-box .reply {
  font-size: 16px;
  color: #000;
}
.author-title .reply-box {
  margin: 10px 0 0 50px;
  background-color: #efefef;
}
</style>



